<?php

require_once('inc/addon.php');
require_once('inc/database.php');

class Addons {

	/**
	 * An associative array of addons that have been instansiated.
	 * @var Addon[]
	 */
	private static $addons = array();

	/**
	 * Returns the highest rated addons of the specified type
 	 * @param String $type The type of addon to query (plugin, action, theme)
 	 * @param int $count The number of results to return
	 * @return Addon[] An ordered list of addons
	 */
	public static function getTopAddons($type, $count = 5) {
		assert($type == 'plugin' || $type == 'action' || $type == 'theme');
		assert(is_int($count));

		$sql  = 'SELECT addon_id FROM addons WHERE addon_type = \'' . $type;
		$sql .= '\' ORDER BY addon_rating DESC LIMIT 0,' . $count;
		$res  = mysql_query($sql);

		$result = array();

		while ($row = mysql_fetch_assoc($res)) {
			$result[] = new Addon((int) $row['addon_id']);
		}

		return $result;
	}

	/**
	 * Returns the most recently added/updated addons of the specified type
 	 * @param String $type The type of addon to query (plugin, action, theme)
 	 * @param int $count The number of results to return
	 * @return Addon[] An ordered list of addons
	 */
	public static function getRecentAddons($type, $count = 5) {
		assert($type == 'plugin' || $type == 'action' || $type == 'theme');
		assert(is_int($count));

		$sql  = 'SELECT addon_id FROM addons WHERE addon_type = \'' . $type;
		$sql .= '\' ORDER BY addon_date DESC LIMIT 0,' . $count;
		$res  = mysql_query($sql);

		$result = array();

		while ($row = mysql_fetch_assoc($res)) {
			$result[] = new Addon((int) $row['addon_id']);
		}

		return $result;
	}

	/**
	 * Retrieves the addon with the specified ID
	 * @param int $id The addon ID to retrieve
	 * @return Addon An addon object corresponding to the specified addon id.
	 */
	public static function getAddon($id) {
		assert(ctype_digit($id));

		if (!isset(self::$addons[$id])) {
			self::$addons[$id] = new Addon($id);
		}

		return self::$addons[$id];
	}

}

?>